import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import { registerMap } from 'echarts/core';
import chinaJson from '../assets/china.json';
import './Map.css';

export const Map: React.FC = () => {
  const [herbs, setHerbs] = useState<any[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const [isLoading, setIsLoading] = useState<boolean>(true);
  
  const mapChartRef = useRef<HTMLDivElement>(null);
  
  // 加载数据
  useEffect(() => {
    const loadData = async () => {
      try {
        setIsLoading(true);
        
        // 加载药材数据
        const herbsResponse = await fetch('/src/data/herbs.json');
        const herbsData = await herbsResponse.json();
        const herbsList = Object.values(herbsData);
        setHerbs(herbsList);
        
        setIsLoading(false);
      } catch (error) {
        console.error('Failed to load data:', error);
        setIsLoading(false);
      }
    };

    loadData();
  }, []);
  
  // 初始化地图
  useEffect(() => {
    if (isLoading || !herbs.length || !mapChartRef.current) return;
    
    // 注册中国地图
    registerMap('china', chinaJson as any);
    
    const mapChart = echarts.init(mapChartRef.current);
    
    // 获取所有分类
    const categories = Array.from(new Set(herbs.map((herb: any) => herb.category)));
    
    // 筛选药材
    const filteredHerbs = selectedCategory === 'all' 
      ? herbs 
      : herbs.filter((herb: any) => herb.category === selectedCategory);
    
    // 准备数据
    const data = filteredHerbs.map((herb: any) => ({
      name: herb.name,
      value: herb.origin,
      category: herb.category,
      herbData: herb
    }));
    
    const option = {
      title: {
        text: '药材产地分布',
        subtext: selectedCategory === 'all' ? '全部药材' : selectedCategory,
        left: 'center',
        textStyle: {
          color: '#333',
          fontFamily: 'SimSun, STSong, serif'
        }
      },
      tooltip: {
        trigger: 'item',
        formatter: (params: any) => {
          const { name, category } = params.data;
          return `${name}<br />类别: ${category}`;
        }
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: ['药材产地'],
        textStyle: {
          color: '#333'
        }
      },
      geo: {
        map: 'china',
        roam: true,
        label: {
          emphasis: {
            show: true
          }
        },
        itemStyle: {
          normal: {
            areaColor: '#f7f4ed',
            borderColor: '#d3c5a7'
          },
          emphasis: {
            areaColor: '#e4bb97'
          }
        }
      },
      series: [
        {
          name: '药材产地',
          type: 'scatter',
          coordinateSystem: 'geo',
          data: data,
          symbolSize: function (val: any) {
            return 12;
          },
          itemStyle: {
            color: function(params: any) {
              const categoryColors: Record<string, string> = {
                '草部': '#4CAF50',
                '木部': '#8D6E63',
                '果部': '#FF9800',
                '菌部': '#9C27B0',
                '石部': '#607D8B'
              };
              
              return categoryColors[params.data.category] || '#2196F3';
            }
          },
          emphasis: {
            label: {
              show: true,
              formatter: '{b}'
            }
          }
        }
      ]
    };
    
    mapChart.setOption(option);
    
    // 点击事件
    mapChart.on('click', 'series', (params: any) => {
      const { herbData } = params.data;
      console.log('Selected herb:', herbData);
      // 这里可以添加点击处理，例如显示详情等
    });
    
    // 响应式调整
    window.addEventListener('resize', () => {
      mapChart.resize();
    });
    
    // 清理函数
    return () => {
      mapChart.dispose();
    };
  }, [herbs, selectedCategory, isLoading]);
  
  // 处理分类选择
  const handleCategoryChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
    setSelectedCategory(e.target.value);
  };
  
  if (isLoading) {
    return (
      <div className="loading">
        <div className="loading-spinner"></div>
        <p>正在加载地图数据...</p>
      </div>
    );
  }
  
  // 获取所有分类
  const categories = Array.from(new Set(herbs.map((herb: any) => herb.category)));
  
  return (
    <div className="map-container">
      <header className="app-header">
        <h1>本草纲目药材产地分布</h1>
      </header>
      
      <div className="map-controls card">
        <div className="control-row">
          <label htmlFor="category-select">药材分类:</label>
          <select 
            id="category-select" 
            value={selectedCategory}
            onChange={handleCategoryChange}
          >
            <option value="all">全部分类</option>
            {categories.map((category: string) => (
              <option key={category} value={category}>
                {category}
              </option>
            ))}
          </select>
        </div>
        
        <div className="control-info">
          <p>
            共显示 <strong>{selectedCategory === 'all' 
              ? herbs.length 
              : herbs.filter(h => h.category === selectedCategory).length}</strong> 种药材
          </p>
        </div>
      </div>
      
      <div className="map-wrapper card">
        <div ref={mapChartRef} className="map-chart"></div>
      </div>
      
      <div className="map-legend card">
        <h3>图例说明</h3>
        <div className="legend-items">
          <div className="legend-item">
            <span className="color-dot" style={{ backgroundColor: '#4CAF50' }}></span>
            <span>草部</span>
          </div>
          <div className="legend-item">
            <span className="color-dot" style={{ backgroundColor: '#8D6E63' }}></span>
            <span>木部</span>
          </div>
          <div className="legend-item">
            <span className="color-dot" style={{ backgroundColor: '#FF9800' }}></span>
            <span>果部</span>
          </div>
          <div className="legend-item">
            <span className="color-dot" style={{ backgroundColor: '#9C27B0' }}></span>
            <span>菌部</span>
          </div>
          <div className="legend-item">
            <span className="color-dot" style={{ backgroundColor: '#607D8B' }}></span>
            <span>石部</span>
          </div>
          <div className="legend-item">
            <span className="color-dot" style={{ backgroundColor: '#2196F3' }}></span>
            <span>其他</span>
          </div>
        </div>
      </div>
    </div>
  );
}; 